<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('shop.gift.quick Search Fields') })"
        >
            <template #default>
                <div class="ml-12">
                    <el-button @click="handleExport" type="primary">导出数据</el-button>
                </div>
            </template>
    </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">
            <!-- 请注意 #test 它是自定义的插槽名称 -->
            <template #test>
                <!-- 还可以继续使用 el-table-column 组件本身的插槽 -->
                <el-table-column prop="user.nickname" label="用户" width="220">
                    <template #default="scope">
                        <div style="display:flex; align-items: center;">
                            <el-image
                                v-if="scope.row.user.avatar"
                                :hide-on-click-modal="true"
                                :preview-teleported="true"
                                :preview-src-list="[fullUrl(scope.row.user.avatar)]"
                                :src="fullUrl(scope.row.user.avatar)"
                                class="ba-table-render-image"
                            ></el-image>
                            <div style="display: flex; flex-direction: column;">
                                <div>{{ scope.row.user.nickname }}</div>
                                <div>{{ scope.row.user.mobile }}</div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
            </template>
            <template #remote>
                <!-- 还可以继续使用 el-table-column 组件本身的插槽 -->
                <el-table-column prop="user.nickname" label="员工" width="220">
                    <template #default="scope">
                        <el-image
                            v-if="scope.row.remoteUserTable.avatar"
                            :hide-on-click-modal="true"
                            :preview-teleported="true"
                            :preview-src-list="[fullUrl(scope.row.remoteUserTable.avatar)]"
                            :src="fullUrl(scope.row.remoteUserTable.avatar)"
                            class="ba-table-render-image"
                        ></el-image>
                        {{ scope.row.remoteUserTable.mobile }}
                    </template>
                </el-table-column>
            </template>
        </Table>

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { fullUrl } from '/@/utils/common'
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from '/@/utils/axios'
import { ElMessage } from 'element-plus'
import { read, writeFileXLSX, utils} from 'xlsx'
import { uuid } from '/@/utils/random'
defineOptions({
    name: 'shop/gift',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
const handleExport = () => {
    const data = baTable.getComSearchData()
    createAxios({
        url: '/admin/shop.Gift/export',
        method: 'get',
        params: {search:data},
    }).then((res) => {
        if (res.data.length > 0) {
            let sheetData = []
            for (const k in res.data) {
                shetData.push({
                    序号: parseInt(k) + 1,
                    四位掩码: res.data[k].gift_code,
                    领取手机号: res.data[k].user.mobile,
                    领取时间: res.data[k].create_time,
                    发放员工: res.data[k].remoteUserTable.mobile,
                    核销状态: res.data[k].gift_status == 2 ? '已核销' : '未核销',
                })
            }
            const ws = utils.json_to_sheet(sheetData)
            const wb = utils.book_new()
            utils.book_append_sheet(wb, ws, 'Sheet1')
            writeFileXLSX(wb, uuid() + '.xlsx')
        } else {
            ElMessage.error('没有数据可以导出')
        }
    })
}
/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/shop.Gift/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('shop.gift.id'), prop: 'id', align: 'center', width: 180, operator: false, sortable: 'custom' },
            { label: t('shop.gift.gift_code'), prop: 'gift_code', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: '领取人', render: 'slot', slotName: 'test', operator: false },
            { label: t('shop.gift.user__nickname'), prop: 'user.nickname', align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tags', operator: 'LIKE', show:false },
            { label: t('shop.gift.user__mobile'), prop: 'user.mobile', align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tags', operator: 'LIKE', show:false },
            { label: '发放人', render: 'slot', slotName: 'remote', operator: false },
            { label: '发放人手机', prop: 'remoteUserTable.mobile', align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tags', operator: 'LIKE', show:false },
            { label: t('shop.gift.gift_status'), prop: 'gift_status', align: 'center', render: 'tag', operator: 'eq', sortable: false, replaceValue: { '1': t('shop.gift.gift_status 1'), '2': t('shop.gift.gift_status 2') } },
            { label: t('shop.gift.status'), prop: 'status', align: 'center', render: 'switch', operator: 'eq', sortable: false, replaceValue: { '0': t('shop.gift.status 0'), '1': t('shop.gift.status 1') } },
            { label: t('shop.gift.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('shop.gift.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', sortable: 'custom', width: 160, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined, 'status'],
    },
    {
        defaultItems: { gift_status: '1', status: '1' },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss">
.ml-12 { margin-left: 12px; }

.ba-table-render-image {
    height: 36px;
    width: 36px;
}
</style>
